#ifndef _UDP_SERVER_HPP
#define _UDP_SERVER_HPP

#include<sys/types.h>
#include<sys/socket.h>
#include<iostream>
#include <unistd.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include"log.hpp"
#include <cstring>
#include<queue>
#include<unordered_map>

#define SIZE 256
class UdpServer
{
public:
    UdpServer(uint16_t port,std::string ip="")
        :_ip(ip),_port(port),_sockfd(-1)
    {}

    ~UdpServer()
    {
        if(_sockfd>=0)
        {
            close(_sockfd);
        }
    }

    bool InitServer()
    {
        _sockfd = socket(AF_INET,SOCK_DGRAM,0);
        if(_sockfd<0)
        {
            logMessage(FATAL,"%d:%s",errno,strerror(errno));
            exit(2);
        }
        // std::cout << "socket create success, sockfd: " << _sockfd << std::endl;

        struct sockaddr_in local;
        bzero(&local,sizeof(local));

        local.sin_family = AF_INET;
        local.sin_port=htons(_port);
        local.sin_addr.s_addr= _ip.empty()? INADDR_ANY:inet_addr(_ip.c_str());

        if(bind(_sockfd,(sockaddr*)(&local),sizeof(local))<0)
        {
            logMessage(FATAL,"%d:%s",errno,strerror(errno));
            exit(2);
        }

        // std::cout << "bind success" << std::endl;
        logMessage(NORMAL, "init udp server done ... %s", strerror(errno));
        return true;
    }

    void start()
    {
        char buffer[SIZE];
        
        
        while(true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t s = recvfrom(_sockfd,buffer,sizeof(buffer)-1,0,(sockaddr*)&peer,&len);


            char result[256];
            char key[64];
            if(s>0)
            {
                buffer[s] = 0;

                uint16_t cli_port = ntohs(peer.sin_port);
                std::string cli_ip = inet_ntoa(peer.sin_addr);

                snprintf(key,sizeof(key),"%s--%d",cli_ip.c_str(),cli_port);
                //std::cout << "client send to # " << buffer << std::endl;
                
                logMessage(NORMAL, "key: %s", key);
                auto it = _users.find(key);
                if(it == _users.end())
                {
                    logMessage(NORMAL, "add new user : %s", key);
                    _users.insert({key,peer});
                }
            }

            for(auto& it:_users)
            {
                std::string sendMessage = key;
                sendMessage+="# ";
                sendMessage+=buffer;

                sendto(_sockfd,sendMessage.c_str(),sendMessage.size(),0,(sockaddr*)&(it.second),sizeof(it.second));
            }

        }
    }
private:
    std::string _ip;
    uint16_t _port;
    int _sockfd;
    std::unordered_map<std::string,struct sockaddr_in> _users;
    std::queue<std::string> messageQueue;
};

#endif